package com.loan.market.base

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.util.SparseArray
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.loan.market.R
import com.loan.market.view.TitleBar

abstract class BaseActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        getView()?.let {
            setContentView(it)
        }

        initUi(savedInstanceState)

        initEvent()

        initData()

        findViewById<TitleBar>(R.id.title_bar)?.setOnLeftClick {
            back()
        }

    }


    abstract fun initUi(savedInstanceState: Bundle?)

    abstract fun initEvent()

    abstract fun initData()

    open fun updateBtn() {}

    open fun back() {
        finish()
    }

    abstract fun getView(): View?

    private lateinit var loading: Dialog

    fun showLoading() {
        if (!this::loading.isInitialized) {
            loading = Dialog(this, R.style.NormalDialog)
            loading.setContentView(R.layout.layout_progress)
            loading.setCanceledOnTouchOutside(false)
        }
        loading.show()
    }


    fun dismissLoading() {
        if (this::loading.isInitialized && loading.isShowing) {
            loading.dismiss()
        }
    }

    private val resultMap = SparseArray<Intent?.(resultCode: Int) -> Unit>()

    fun startResult(id: Int, intent: Intent, block: Intent?.(resultCode: Int) -> Unit = {}) {
        val result = resultMap[id]
        if (result == null) {
            resultMap[id] = block
        }
        startActivityForResult(intent, id)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        resultMap[requestCode]?.invoke(data, resultCode)
    }

    open val activity = this

    override fun onDestroy() {
        super.onDestroy()
        dismissLoading()
    }

}